#include "myClipboard.h"
#include "ui_myclipboard.h"
#include "clipboardStorage.h"
#include "textItemWidget.h"
#include "imageItemWidget.h"
#include "fileItemWidget.h"
#include "urlItemWidget.h"
#include "QListWidgetItem"
#include "QDebug"
#include <QDesktopServices>
#include <QUrl>
#include <QFileIconProvider>
#include <QIcon>
#include "QDesktopWidget"
#include <QGraphicsDropShadowEffect>
#include <QMouseEvent>
#include <qt_windows.h>
#include <QScrollBar>
#include <QButtonGroup>
#include <QAction>


/**
 * 剪切板组件的添加(根据不同类型的item使用不同的组件)
 * @brief MyClipBoard::MyClipBoard
 * @param parent
 */

MyClipBoard::MyClipBoard(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyClipBoard),
      allButton(new QPushButton("全部",this)),
      textButton(new QPushButton("文本",this)),
      urlButton(new QPushButton("链接",this)),
      fileButton(new QPushButton("文件",this)),
      imageButton(new QPushButton("图片",this)),
      favoriteButton(new QPushButton("收藏",this))
{
    setAttribute(Qt::WA_TranslucentBackground, true); // 设置窗口背景透明
    clipboardManager = new ClipboardManager();
    clipboardManager->startMonitoring();

    // 连接信号和槽
    connect(clipboardManager, SIGNAL(updateItem(ClipboardType, bool, bool)), this, SLOT(updateListWidget(ClipboardType, bool, bool))); // 增、删
    connect(clipboardManager->getStorage(), &ClipboardStorage::updateItem, this, [this]() { // 改
        updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), false);
    });


    connect(allButton, &QPushButton::clicked, this, &MyClipBoard::setAllStatus);
    connect(textButton, &QPushButton::clicked, this, &MyClipBoard::setTextStatus);
    connect(urlButton, &QPushButton::clicked, this, &MyClipBoard::setUrlStatus);
    connect(fileButton, &QPushButton::clicked, this, &MyClipBoard::setFileStatus);
    connect(imageButton, &QPushButton::clicked, this, &MyClipBoard::setImageStatus);
    connect(favoriteButton, &QPushButton::clicked, this, &MyClipBoard::setFavoriteStatus);


    ui->setupUi(this);

    // 连接搜索框的文本变化事件，触发更新和过滤
    connect(ui->lineEditSearch, &QLineEdit::textChanged, this, [this]() {
        // 确保根据当前分类和收藏状态触发更新
        updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
    });

    ui->buttonLayout->setContentsMargins(5, 0, 5, 0);

    ui->buttonLayout->addWidget(allButton);
    ui->buttonLayout->addWidget(textButton);
    ui->buttonLayout->addWidget(urlButton);
    ui->buttonLayout->addWidget(fileButton);
    ui->buttonLayout->addWidget(imageButton);
    ui->buttonLayout->addWidget(favoriteButton);
    updateListWidget(ClipboardType::All, false, false);

    // 设置窗口为无边框窗口始终置顶
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    QString buttonStyle = 
        "QPushButton {"
        "   padding: 5px 15px;"
        "   border: none;"
        "   border-radius: 4px;"
        "   background-color: #f0f0f0;"
        "   color: #666666;"
        "   font-size: 12px;"
        "   font-family: 'Dengxian';"
        "   font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "   background-color: #e0e0e0;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #d0d0d0;"
        "}"
        "QPushButton:checked {"
        "   background-color: #9F8AED;"
        "   color: white;"
        "}"
        "QPushButton:disabled {"
        "   background-color: #f5f5f5;"
        "   color: #999999;"
        "}";

    // 创建按钮组并添加按钮
    buttonGroup = new QButtonGroup(this);
    buttonGroup->addButton(allButton);
    buttonGroup->addButton(textButton);
    buttonGroup->addButton(urlButton);
    buttonGroup->addButton(fileButton);
    buttonGroup->addButton(imageButton);
    buttonGroup->addButton(favoriteButton);
    
    // 设置按钮组为互斥
    buttonGroup->setExclusive(true);

    // 设置按钮为可选中状态
    allButton->setCheckable(true);
    textButton->setCheckable(true);
    urlButton->setCheckable(true);
    fileButton->setCheckable(true);
    imageButton->setCheckable(true);
    favoriteButton->setCheckable(true);

    // 默认选中"全部"按钮
    allButton->setChecked(true);

    // 应用样式
    allButton->setStyleSheet(buttonStyle);
    textButton->setStyleSheet(buttonStyle);
    urlButton->setStyleSheet(buttonStyle);
    fileButton->setStyleSheet(buttonStyle);
    imageButton->setStyleSheet(buttonStyle);
    favoriteButton->setStyleSheet(buttonStyle);

    // 在构造函数中添加
    QString searchStyle = 
        "QLineEdit {"
        "   margin: 0px 5px;"
        "   padding: 8px 15px;"
        "   padding-left: 0px;"
        "   border: 1px solid #e0e0e0;"
        "   border-radius: 6px;"
        "   background-color: #f5f5f5;"
        "   color: #333333;"
        "   font-size: 12px;"
        "   font-family: 'Dengxian';"
        "   selection-background-color: #5030E5;"
        "   selection-color: white;"
        "}"
        "QLineEdit:hover {"
        "   border: 1px solid #d0d0d0;"
        "   background-color: white;"
        "}"
        "QLineEdit:focus {"
        "   border: 1px solid #5030E5;"
        "   background-color: white;"
        "}";

    // 设置搜索框样式
    ui->lineEditSearch->setStyleSheet(searchStyle);
    
    // 设置搜索框占位符文本
    ui->lineEditSearch->setPlaceholderText("搜索");

    // 添加搜索图标
    QAction* searchAction = new QAction(ui->lineEditSearch);
    searchAction->setIcon(QIcon(":/icon/icon/search_icon.png"));
    ui->lineEditSearch->addAction(searchAction, QLineEdit::LeadingPosition);
    searchAction->setIconText(""); // 确保图标没有文本

}

MyClipBoard::~MyClipBoard()
{
    clipboardManager->~ClipboardManager();
    delete ui;
}

void MyClipBoard::updateListWidget(ClipboardType type, bool favorite, bool updatePosition) {
    // 记录当前滚动位置
    int scrollPosition = ui->listWidget->verticalScrollBar()->value();

    // 清空列表并刷新数据
    ui->listWidget->clear();

    // 获取并修整搜索框的内容
    QString searchQuery = ui->lineEditSearch->text().trimmed();

    const auto& items = clipboardManager->getAllItems(type, favorite, searchQuery);

    for (const auto& item : items) {
        if (item.getType() == ClipboardType::Text) {
            addTextItem(item);
        } else if (item.getType() == ClipboardType::Image) {
            addImageItem(item);
        } else if (item.getType() == ClipboardType::File) {
            addFileItem(item);
        } else if (item.getType() == ClipboardType::Url) {
            addUrlItem(item);
        }
    }

    // 恢复滚动位置
    if(updatePosition == false) {
        ui->listWidget->verticalScrollBar()->setValue(scrollPosition);
    }
}



// 调用文本的组件将文本展示出来
void MyClipBoard::addTextItem(const ClipboardItem& item){
    TextItemWidget *listItemWidget = new TextItemWidget(item);  // 创建 ListItemWidget
    QListWidgetItem *listItem = new QListWidgetItem();  // 创建空项
    listItem->setSizeHint(listItemWidget->sizeHint());
    ui->listWidget->addItem(listItem);  // 添加空项到列表
    ui->listWidget->setItemWidget(listItem, listItemWidget);  // 将 ListItemWidget 设置为该空项的内容

    connect(listItemWidget, &TextItemWidget::copyClicked, [this, item]() {
        clipboardManager->copyItem(item);
    });
    connect(listItemWidget, &TextItemWidget::deleteClicked, [this, item]() {
        clipboardManager->deleteItem(item);
    });
    connect(listItemWidget, &TextItemWidget::searchClicked, [this, item]() {
        clipboardManager->searchItem(item);
    });
    connect(listItemWidget, &TextItemWidget::getDetailDoubleCliked, [this, item]() {
        clipboardManager->getItemDetail(item);
    });
    connect(listItemWidget, &TextItemWidget::favoriteClicked, [this, item]() {
        clipboardManager->favoriteItem(item);
    });
}

// 调用图片的组件将图片展示出来
void MyClipBoard::addImageItem(const ClipboardItem& item){
   ImageItemWidget *imageItemWidget = new ImageItemWidget(item);
   QListWidgetItem *listItem = new QListWidgetItem();
   listItem->setSizeHint(imageItemWidget->sizeHint());
   ui->listWidget->addItem(listItem);  // 添加空项到列表
   ui->listWidget->setItemWidget(listItem, imageItemWidget);  // 将 ListItemWidget 设置为该空项的内容

   connect(imageItemWidget, &ImageItemWidget::copyClicked, [this, item]() {
       clipboardManager->copyItem(item);
   });
   connect(imageItemWidget, &ImageItemWidget::deleteClicked, [this, item]() {
       clipboardManager->deleteItem(item);
   });
   connect(imageItemWidget, &ImageItemWidget::getDetailDoubleCliked, [this, item]() {
       clipboardManager->getItemDetail(item);
   });
   connect(imageItemWidget, &ImageItemWidget::favoriteClicked, [this, item]() {
       clipboardManager->favoriteItem(item);
   });
}


// 调用文件的组件将文件展示出来
void MyClipBoard::addFileItem(const ClipboardItem& item) {
    FileItemWidget *fileItemWidget = new FileItemWidget(item); // 创建 FileItemWidget
    QListWidgetItem *listItem = new QListWidgetItem(); // 创建空项
    listItem->setSizeHint(fileItemWidget->sizeHint());
    ui->listWidget->addItem(listItem); // 添加空项到列表
    ui->listWidget->setItemWidget(listItem, fileItemWidget); // 将 FileItemWidget 设置为该空项的内容

    connect(fileItemWidget, &FileItemWidget::copyClicked, [this, item]() {
        clipboardManager->copyItem(item);
    });
    connect(fileItemWidget, &FileItemWidget::deleteClicked, [this, item]() {
        clipboardManager->deleteItem(item);
    });
    connect(fileItemWidget, &FileItemWidget::openClicked, [this,item]() {
        clipboardManager->openItem(item);
    });
    connect(fileItemWidget, &FileItemWidget::favoriteClicked, [this,item]() {
        clipboardManager->favoriteItem(item);
    });
}


// 调用网站URL的组件将URL等展示出来
void MyClipBoard::addUrlItem(const ClipboardItem& item) {
    UrlItemWidget *urlItemWidget = new UrlItemWidget(item);
    QListWidgetItem *listItem = new QListWidgetItem();
    listItem->setSizeHint(urlItemWidget->sizeHint());
    ui->listWidget->addItem(listItem);
    ui->listWidget->setItemWidget(listItem, urlItemWidget);

    connect(urlItemWidget, &UrlItemWidget::copyClicked, [this, item]() {
        clipboardManager->copyItem(item);
    });
    connect(urlItemWidget, &UrlItemWidget::openClicked, [this, item]() {
        clipboardManager->openItem(item);
    });
    connect(urlItemWidget, &UrlItemWidget::deleteClicked, [this, item]() {
        clipboardManager->deleteItem(item);
    });
    connect(urlItemWidget, &UrlItemWidget::getDetailDoubleCliked, [this, item]() {
        clipboardManager->getItemDetail(item);
    });
    connect(urlItemWidget, &UrlItemWidget::favoriteClicked, [this, item]() {
        clipboardManager->favoriteItem(item);
    });
}

//关闭按钮
void MyClipBoard::on_pushButton_clicked()
{
     this->close();
}

void MyClipBoard::on_pushButton_2_clicked()
{
     this->showMinimized();
}

void MyClipBoard::setAllStatus() {
    allButton->setChecked(true);
    textButton->setChecked(false);
    urlButton->setChecked(false);
    fileButton->setChecked(false);
    imageButton->setChecked(false);
    favoriteButton->setChecked(false);
    clipboardManager->setClipboardType(ClipboardType::All);
    clipboardManager->setClipboardFavorite(false);
    updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
}

void MyClipBoard::setTextStatus() {
    clipboardManager->setClipboardType(ClipboardType::Text);
    clipboardManager->setClipboardFavorite(false);
    updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
}

void MyClipBoard::setUrlStatus() {
    clipboardManager->setClipboardType(ClipboardType::Url);
    clipboardManager->setClipboardFavorite(false);
    updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
}

void MyClipBoard::setFileStatus() {
    clipboardManager->setClipboardType(ClipboardType::File);
    clipboardManager->setClipboardFavorite(false);
    updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
}

void MyClipBoard::setImageStatus() {
    clipboardManager->setClipboardType(ClipboardType::Image);
    clipboardManager->setClipboardFavorite(false);
    updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
}

void MyClipBoard::setFavoriteStatus() {
    clipboardManager->setClipboardFavorite(true);
    updateListWidget(clipboardManager->getClipboardType(), clipboardManager->getCLipboardFavorite(), true);
    qDebug()<<"收藏";
}
//处理鼠标按下事件--无边框窗口拖拽移动的解决办法
void MyClipBoard::mousePressEvent(QMouseEvent* event)
{
    //释放当前捕获的鼠标，若成功释放返回true
    if (ReleaseCapture())
    {
        QWidget* pWindow = this->window();	//获取窗口指针
        if (pWindow->isTopLevel())	//检查获取到的窗口是否是一个顶级窗口（即不是其他窗口的子控件）
        {
            //如果窗口是顶级窗口，使用 SendMessage 函数向父窗口句柄发送一个 WM_SYSCOMMAND 消息，该消息指示窗口开始移动操作。
            SendMessage(HWND(pWindow->winId()), WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }
    }
    event->ignore();
}

